package hotel.switchs.oversea.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.dto.switchs.SwitchMasterRoomTemplateDto;
import hotel.base.oversea.dto.switchs.SwitchRoomTypeDto;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.JSONUtils;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.vo.CreateRoomResultVo;
import hotel.base.oversea.vo.ResultStatusInfoVo;
import hotel.switchs.oversea.api.VO.*;
import hotel.switchs.oversea.api.VO.request.*;
import hotel.switchs.oversea.api.VO.request.SaleRuleVo;
import hotel.switchs.oversea.api.entity.*;
import hotel.switchs.oversea.biz.config.service.RedisService;
import hotel.switchs.oversea.biz.mapper.*;
import hotel.switchs.oversea.biz.service.SwitchBasicRoomTypeService;
import hotel.switchs.oversea.biz.utils.SwitchsHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lmf
 * @Date 2020/5/16 16:17
 **/
@Service
@Slf4j
public class SwitchBasicRoomTypeServiceImpl extends BaseServiceImpl implements SwitchBasicRoomTypeService {
    Logger logger = LoggerFactory.getLogger(SwitchBasicRoomTypeServiceImpl.class);
    @Autowired
    private SwitchBasicRoomTypeMapper switchBasicRoomTypeMapper;
    @Autowired
    private SwitchRoomBedInfoMapper switchRoomBedInfoMapper;
    @Autowired
    private SwitchRoomBroadNetMapper switchRoomBroadNetMapper;
    @Autowired
    private SwitchRoomInfoMapper switchRoomInfoMapper;
    @Autowired
    private SwitchRoomPictureMapper switchRoomPictureMapper;
    @Autowired
    private SwitchRoomTypeFacilityMapper switchRoomTypeFacilityMapper;
    @Autowired
    private SwitchRoomTypeMapper switchRoomTypeMapper;
    @Autowired
    private SwitchHotelInfoMapper switchBasicRoomTypes;

    @Autowired
    private RedisService redisService;


    @Value("${profile.type}")
    private String profile;

    /**
     * @param hotelId
     * @return 获取母物理房型列表
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> getDltBasicRoomList(int hotelId) {
        Map<String, Object> data = new HashMap<>();
        data.put("hotelID", hotelId);
        String result = SwitchsHttpUtils.sendRequest(data, "getdltbasicroomlist", profile);
        //对结构进行格式化
        JSONObject jsonObject= JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(jsonObject.getString("resultStatus"),ResultStatusInfoVo.class);
        System.out.println(result);
        if (resultStatusInfoVo.getResultCode() != 0) {
            logger.info("获取母物理房型列表错误信息{}", resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }
        List<DltBasicRoomTypeVo> dltBasicRoomTypeVos=JacksonUtil.jsonToList(jsonObject.getString("dltBasicRoomTypeEntityList"), DltBasicRoomTypeVo.class);
        return new Result<>(dltBasicRoomTypeVos);
    }
    /**
     * @param hotelId
     * @return 获取母物理房型列表
     */
    @Override
    public Result<Object> getHotelBasicRoomList(int hotelId){
        Map<String, Object> data = new HashMap<>();
        data.put("hotelID", hotelId);
        String result = SwitchsHttpUtils.sendRequest(data, "getdltbasicroomlist", profile);
        //对结构进行格式化
        JSONObject jsonObject= JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(jsonObject.getString("resultStatus"),ResultStatusInfoVo.class);
        System.out.println(result);
        if (resultStatusInfoVo.getResultCode() != 0) {
            logger.info("获取母物理房型列表错误信息{}", resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }
        List<SwitchBasicRoomType> switchBasicRoomTypes = new ArrayList<>();
        List<DltBasicRoomTypeVo> dltBasicRoomTypeVos=JacksonUtil.jsonToList(jsonObject.getString("dltBasicRoomTypeEntityList"), DltBasicRoomTypeVo.class);
        if(ObjectUtils.isEmpty(dltBasicRoomTypeVos)||dltBasicRoomTypeVos.size()<1){
            for(int i=0;i<3;i++){
                try {
                    Thread.sleep(1000);
                    result = SwitchsHttpUtils.sendRequest(data, "getdltbasicroomlist", profile);
                    jsonObject= JSONObject.parseObject(result);
                    dltBasicRoomTypeVos=JacksonUtil.jsonToList(jsonObject.getString("dltBasicRoomTypeEntityList"), DltBasicRoomTypeVo.class);
                    if(!ObjectUtils.isEmpty(dltBasicRoomTypeVos)){
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (DltBasicRoomTypeVo dltBasicRoomTypeVo : dltBasicRoomTypeVos) {
            SwitchBasicRoomType switchBasicRoomType = new SwitchBasicRoomType();
            switchBasicRoomType.setId(String.valueOf(UUID.randomUUID()));
            switchBasicRoomType.setBasicRoomName(dltBasicRoomTypeVo.getBasicRoomName());
            switchBasicRoomType.setBasicRoomNameEn(dltBasicRoomTypeVo.getBasicRoomNameEn());
            //母酒店id
            switchBasicRoomType.setMasterHotelId(dltBasicRoomTypeVo.getHotelID());
            //子酒店id
            switchBasicRoomType.setHotelId(hotelId);
            switchBasicRoomType.setIsAdd(dltBasicRoomTypeVo.getIsAdd().equals("T") ? 1 : 0);
            switchBasicRoomType.setMasterBasicRoomId(dltBasicRoomTypeVo.getMasterBasicRoomId());
            switchBasicRoomTypes.add(switchBasicRoomType);
        }
        sb.append("'" + hotelId + "'");//拼接单引号,到数据库后台用in查询.
        //旧数据删除，插入新数据
        Map<String,String> idsMap = new HashMap();
        idsMap.put("ids", sb.toString());
        int roDel = switchBasicRoomTypeMapper.deleteBatch(idsMap);
        if(roDel != -1){
            if(!ObjectUtils.isEmpty(switchBasicRoomTypes)&&switchBasicRoomTypes.size()>0){
                switchBasicRoomTypeMapper.insertList(switchBasicRoomTypes);
            }
        }
        return new Result<>();
    }

    /**
     * 保存物理房型数据
     * Map<String,List<DltBasicRoomTypeVo>> dltBasicRoomTypeVosMap  --->  key = 子酒店ID hotelId  value = List<DltBasicRoomTypeVo>
     *
     * @return
     */
    @Override
    public Result<Object> saveRoomTypeInfos(Map<String, List<DltBasicRoomTypeVo>> dltBasicRoomTypeVosMap) {
        List<SwitchBasicRoomType> switchBasicRoomTypes = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int j = 0;
        Map<String, SwitchMasterRoomTemplateDto> pullDtoMap = new HashMap<>();
        for (Map.Entry<String, List<DltBasicRoomTypeVo>> entry : dltBasicRoomTypeVosMap.entrySet()) {
            List<DltBasicRoomTypeVo> dltBasicRoomTypeVos = entry.getValue();
            String hotelId = entry.getKey();
            //封装属性表单数据
            for (DltBasicRoomTypeVo dltBasicRoomTypeVo : dltBasicRoomTypeVos) {
                SwitchBasicRoomType switchBasicRoomType = new SwitchBasicRoomType();
                switchBasicRoomType.setId(String.valueOf(UUID.randomUUID()));
                switchBasicRoomType.setBasicRoomName(dltBasicRoomTypeVo.getBasicRoomName());
                switchBasicRoomType.setBasicRoomNameEn(dltBasicRoomTypeVo.getBasicRoomNameEn());
                //母酒店id
                switchBasicRoomType.setMasterHotelId(dltBasicRoomTypeVo.getHotelID());
                //子酒店id
                switchBasicRoomType.setHotelId(Integer.valueOf(entry.getKey()));
                switchBasicRoomType.setIsAdd(dltBasicRoomTypeVo.getIsAdd().equals("T") ? 1 : 0);
                switchBasicRoomType.setMasterBasicRoomId(dltBasicRoomTypeVo.getMasterBasicRoomId());
                switchBasicRoomTypes.add(switchBasicRoomType);

                //构造缓存数据
                SwitchMasterRoomTemplateDto switchMasterRoomTemplateDto = new SwitchMasterRoomTemplateDto();
                switchMasterRoomTemplateDto.setHotelId(switchBasicRoomType.getHotelId());
                switchMasterRoomTemplateDto.setMasterHotelId(switchBasicRoomType.getMasterHotelId());
                switchMasterRoomTemplateDto.setMasterBasicRoomId(switchBasicRoomType.getMasterBasicRoomId());
                pullDtoMap.put(String.valueOf(switchBasicRoomType.getMasterBasicRoomId()), switchMasterRoomTemplateDto);

            }
            sb.append("'" + hotelId + "'");//拼接单引号,到数据库后台用in查询.
            if (j != dltBasicRoomTypeVosMap.size() - 1) {
                sb.append(",");
            }
            j += 1;
        }
        //旧数据删除，插入新数据
        Map idsMap = new HashMap();
        idsMap.put("ids", sb.toString());
        int roDel = switchBasicRoomTypeMapper.deleteBatch(idsMap);
        if(roDel != -1){
            switchBasicRoomTypeMapper.insertList(switchBasicRoomTypes);
        }

        //缓存母物理房型数据，构造数据，方便定时器跑批创建子物理房型接口
        //数据接口  Map<string,SwitchMasterRoomTemplateDto>  key = 母物理房型id     value = SwitchMasterRoomTemplateDto
        Map<String, SwitchMasterRoomTemplateDto> redisMap = (Map<String, SwitchMasterRoomTemplateDto>) redisService.get(CommonConstants.SWITCH_MASTER_ROOM_HOTEL_AND_MASTER_INFO);
        if (null != redisMap && redisMap.size() > 0) {
            redisMap.putAll(pullDtoMap);//加入putall覆盖旧数据
        } else {
            redisMap = pullDtoMap;
        }
        redisService.set(CommonConstants.SWITCH_MASTER_ROOM_HOTEL_AND_MASTER_INFO, redisMap);


        return new Result<>();
    }


    /**
     * 获取酒店房型静态信息列表
     *
     * @param map List<RoomStaticInfoVo>
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> getHotelRoomStaticInfo(Map<String, Object> map, int masterHotelID) {
        String result = SwitchsHttpUtils.sendRequest(map, "gethotelroomstaticinfo", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(jsonObject.getString("resultStatus"), ResultStatusInfoVo.class);
        if (resultStatusInfoVo.getResultCode() != 0) {
            logger.info("获取酒店房型静态信息列表错误信息{}", resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }
        String roomStaticInfo = JSON.parseObject(result).getJSONObject("roomStaticInfos").getString("roomStaticInfo");
        roomStaticInfo = roomStaticInfo.replace("[{}]", "[]");
        List<RoomStaticInfoVo> roomStaticInfoList = JSON.parseObject(roomStaticInfo, List.class);
        if (null != roomStaticInfoList && roomStaticInfoList.size() > 0) {
            return new Result<>(roomStaticInfoList);
        }
        //封装成表单数据
        return new Result<>();
    }

    /**
     * 保存静态物理房型数据
     */
    @Override
    public Result<Object> saveBasicRoomData(Map<String, List<RoomStaticInfoVo>> roomStaticInfoListMap) {
        for (Map.Entry<String, List<RoomStaticInfoVo>> entry : roomStaticInfoListMap.entrySet()) {
            List<RoomStaticInfoVo> roomStaticInfoList = entry.getValue();
            int subHotelId = Integer.valueOf(entry.getKey().split(",")[0]);
            int masterHotelID = Integer.valueOf(entry.getKey().split(",")[1]);
            //封装成表单数据
            List<SwitchRoomBedInfo> switchRoomBedInfos = new ArrayList<>();
            List<SwitchRoomBroadNet> switchRoomBroadNets = new ArrayList<>();
            List<SwitchRoomInfo> switchRoomInfos = new ArrayList<>();
            List<SwitchRoomPicture> switchRoomPictures = new ArrayList<>();
            List<SwitchRoomType> switchRoomTypes = new ArrayList<>();
            /*Map<String, SwitchRoomTypeDto> redisMap = new HashMap<>();*/
            List<SwitchRoomTypeFacility> switchRoomTypeFacilities = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            switchtab:
            for (RoomStaticInfoVo roomStaticInfoVo : roomStaticInfoList) {

                //获取床型内容
                RoomTypeInfosVo roomTypeInfosVo = roomStaticInfoVo.getRoomTypeInfos();
                List<RoomTypeInfoVo> roomTypeInfoVos = null;
                if (null != roomTypeInfosVo) {
                    roomTypeInfoVos = roomTypeInfosVo.getRoomTypeInfo();
                    if (ObjectUtils.isEmpty(roomTypeInfoVos) || roomTypeInfoVos.size() < 1) {
                        continue switchtab;
                    }
                } else {
                    continue switchtab;
                }


                for (RoomTypeInfoVo roomTypeInfoVo : roomTypeInfoVos) {
                    SwitchRoomType switchRoomType = new SwitchRoomType();
                    switchRoomType.setRoomTypeId(roomTypeInfoVo.getRoomTypeId());
                    /*if(!ObjectUtils.isEmpty(switchRoomTypeMapper.selectOne(switchRoomType))){
                        continue;
                    }*/
                    switchRoomType.setId(String.valueOf(UUID.randomUUID()));
                    switchRoomType.setAreaRange(roomTypeInfoVo.getAreaRange());
                    switchRoomType.setFloorRange(roomTypeInfoVo.getFloorRange());
                    //0表示无窗，1表示部分有窗，2表示有窗，null表示有窗
                    String hasWindow = ObjectUtils.isEmpty(roomTypeInfoVo.getHasWindow()) ? "2" : roomTypeInfoVo.getHasWindow();
                    switchRoomType.setHasWindow(Integer.valueOf(hasWindow));
                    Integer roomQuantity = roomTypeInfoVo.getRoomQuantity() == null ? 0 : Integer.valueOf(roomTypeInfoVo.getRoomQuantity());
                    switchRoomType.setRoomQuantity(roomQuantity);
                    switchRoomType.setMasterBasicRoomTypeId(roomTypeInfoVo.getMasterBasicRoomTypeId());
                    switchRoomType.setRootTypeName(roomTypeInfoVo.getRoomTypeName());
                    switchRoomType.setHotelId(subHotelId);
                    switchRoomType.setState(0);
                    switchRoomType.setMasterHotelId(masterHotelID);
                    switchRoomTypes.add(switchRoomType);

                    SwitchRoomTypeDto srtDto = new SwitchRoomTypeDto();
                    srtDto.setRoomTypeId(switchRoomType.getRoomTypeId());
                    srtDto.setId(switchRoomType.getId());
                    srtDto.setAreaRange(switchRoomType.getAreaRange());
                    srtDto.setFloorRange(switchRoomType.getFloorRange());
                    srtDto.setHasWindow(switchRoomType.getHasWindow());
                    srtDto.setRoomQuantity(switchRoomType.getRoomQuantity());
                    srtDto.setMasterBasicRoomTypeId(switchRoomType.getMasterBasicRoomTypeId());
                    srtDto.setRootTypeName(switchRoomType.getRootTypeName());
                    srtDto.setHotelId(switchRoomType.getHotelId());
                    /*redisMap.put(String.valueOf(srtDto.getHotelId())+String.valueOf(srtDto.getRoomTypeId()),srtDto);*/

                    //获取房型的相关设施
                    FacilitiesVo facilitiesVo = roomTypeInfoVo.getFacilities();
                    List<FacilityVo> facilityVos = null;
                    if (null != facilitiesVo) {
                        facilityVos = facilitiesVo.getFacility();
                        if (ObjectUtils.isEmpty(facilityVos) || facilityVos.size() == 0) {
                            continue;
                        }
                    } else {
                        continue;
                    }

                    for (FacilityVo facilityVo : facilityVos) {
                        List<FacilityItemVo> facilityItemVos = facilityVo.getFacilityItem();
                        if (ObjectUtils.isEmpty(facilityItemVos) || facilityItemVos.size() == 0) {
                            continue;
                        }
                        for (FacilityItemVo facilityItemVo : facilityItemVos) {
                            SwitchRoomTypeFacility switchRoomTypeFacility = new SwitchRoomTypeFacility();
                            switchRoomTypeFacility.setId(String.valueOf(UUID.randomUUID()));
                            switchRoomTypeFacility.setName(facilityItemVo.getName());
                            switchRoomTypeFacility.setStatus(Integer.valueOf(facilityItemVo.getStatus()));
                            switchRoomTypeFacility.setRoomTypeId(roomTypeInfoVo.getRoomTypeId());
                            switchRoomTypeFacilities.add(switchRoomTypeFacility);
                        }
                    }
                    //获取房型的图片
                    PicturesVo picturesVo = roomTypeInfoVo.getPictures();
                    List<PictureVo> pictureVos = null;
                    if (null != picturesVo) {
                        pictureVos = picturesVo.getPicture();
                        if (ObjectUtils.isEmpty(pictureVos) || pictureVos.size() == 0) {
                            continue;
                        }
                    } else {
                        continue;
                    }

                    for (PictureVo pictureVo : pictureVos) {
                        SwitchRoomPicture switchRoomPicture = new SwitchRoomPicture();
                        switchRoomPicture.setId(String.valueOf(UUID.randomUUID()));
                        switchRoomPicture.setHotelId(subHotelId);
                        switchRoomPicture.setCaption(pictureVo.getCaption());
                        switchRoomPicture.setRoomTypeId(roomTypeInfoVo.getRoomTypeId());
                        switchRoomPicture.setUrl(pictureVo.getURL());
                        switchRoomPictures.add(switchRoomPicture);
                    }
                    //获取床型信息
                    RoomBedInfosVo roomBedInfosVo = roomTypeInfoVo.getRoomBedInfos();
                    List<RoomBedInfoVo> roomBedInfoVos = null;
                    if (null != roomBedInfosVo) {
                        roomBedInfoVos = roomBedInfosVo.getRoomBedInfo();
                        if (ObjectUtils.isEmpty(roomBedInfoVos) || roomBedInfoVos.size() == 0) {
                            continue;
                        }
                    } else {
                        continue;
                    }

                    for (RoomBedInfoVo roomBedInfoVo : roomBedInfoVos) {
                        List<BedInfoVo> bedInfoVos = roomBedInfoVo.getBedInfo();
                        if (ObjectUtils.isEmpty(bedInfoVos) || bedInfoVos.size() == 0) {
                            continue;
                        }
                        for (BedInfoVo bedInfoVo : bedInfoVos) {
                            SwitchRoomBedInfo switchRoomBedInfo = new SwitchRoomBedInfo();
                            switchRoomBedInfo.setHotelId(subHotelId);
                            switchRoomBedInfo.setId(String.valueOf(UUID.randomUUID()));
                            switchRoomBedInfo.setBedWidth(bedInfoVo.getBedWidth());
                            switchRoomBedInfo.setName(bedInfoVo.getName());
                            switchRoomBedInfo.setNumberOfBeds(bedInfoVo.getNumberOfBeds());
                            switchRoomBedInfo.setRoomTypeId(roomTypeInfoVo.getRoomTypeId());
                            switchRoomBedInfos.add(switchRoomBedInfo);
                        }
                    }
                }
                //售卖房型信息
                RoomInfosVo roomInfosVo = roomStaticInfoVo.getRoomInfos();
                List<RoomInfoVo> roomInfoVos = null;
                if (null != roomInfosVo) {
                    roomInfoVos = roomInfosVo.getRoomInfo();
                    if (ObjectUtils.isEmpty(roomInfoVos) || roomInfoVos.size() < 1) {
                        continue;
                    }
                } else {
                    continue;
                }

                for (RoomInfoVo roomInfoVo : roomInfoVos) {
                    SwitchRoomInfo switchRoomInfo = new SwitchRoomInfo();
                    switchRoomInfo.setRoomId(roomInfoVo.getRoomId());
                    if (!ObjectUtils.isEmpty(switchRoomInfoMapper.selectOne(switchRoomInfo))) {
                        continue;
                    }

                    switchRoomInfo.setId(String.valueOf(UUID.randomUUID()));
                    switchRoomInfo.setBasicRoomTypeId(roomInfoVo.getBasicRoomTypeId());
                    switchRoomInfo.setMasterBasicRoomTypeId(roomInfoVo.getMasterBasicRoomTypeId());
                    switchRoomInfo.setRoomName(roomInfoVo.getRoomName());
                    switchRoomInfo.setExtraBedFee(roomInfoVo.getExtraBedFee());
                    switchRoomInfo.setMaxAudltOccupancy(roomInfoVo.getMaxAudltOccupancy());
                    switchRoomInfo.setMaxChildrenOccupancy(roomInfoVo.getMaxChildrenOccupancy());
                    switchRoomInfo.setSmoking(roomInfoVo.getSmoking());
                    switchRoomInfos.add(switchRoomInfo);
                    //获取售卖房型的宽带信息
                    BroadNetVo broadNetVo = roomInfoVo.getBroadNet();
                    if (!ObjectUtils.isEmpty(broadNetVo)) {
                        SwitchRoomBroadNet switchRoomBroadNet = new SwitchRoomBroadNet();
                        switchRoomBroadNet.setId(String.valueOf(UUID.randomUUID()));
                        switchRoomBroadNet.setHotelId(subHotelId);
                        switchRoomBroadNet.setRoomId(roomInfoVo.getRoomId());
                        switchRoomBroadNet.setHasBroadnet(broadNetVo.getHasBroadnet().equals("T") ? 1 : 0);
                        switchRoomBroadNet.setHasWirelessBroadnet(broadNetVo.getHasWirelessBroadnet().equals("T") ? 1 : 0);
                        switchRoomBroadNet.setWiredBroadnetFee(Double.parseDouble(broadNetVo.getWiredBroadnetFee()));
                        switchRoomBroadNet.setHasWiredBroadnet(broadNetVo.getHasWiredBroadnet().equals("T") ? 1 : 0);
                        switchRoomBroadNet.setWiredBroadnetRoom(broadNetVo.getWirelessBroadnetRoom().equals("T") ? 1 : 0);
                        switchRoomBroadNet.setWirelessBroadnetFee(Double.parseDouble(broadNetVo.getWirelessBroadnetFee()));
                        switchRoomBroadNets.add(switchRoomBroadNet);
                    }
                }
            }
            Map idsMap = new HashMap();
            idsMap.put("ids", String.valueOf(subHotelId));
            if (switchRoomBedInfos.size() > 0) {
                //旧数据删除，插入新数据
                if(-1!=switchRoomBedInfoMapper.deleteBatch(idsMap)){
                    switchRoomBedInfoMapper.insertList(switchRoomBedInfos);
                }
            }
            if (switchRoomInfos.size() > 0) {
                //旧数据删除，插入新数据
                if(-1!=switchRoomInfoMapper.deleteBatch(idsMap)){
                    switchRoomInfoMapper.insertList(switchRoomInfos);
                }
            }
            if (switchRoomBroadNets.size() > 0) {
                //旧数据删除，插入新数据
                if(-1!=switchRoomBroadNetMapper.deleteBatch(idsMap)){
                    switchRoomBroadNetMapper.insertList(switchRoomBroadNets);
                }
            }
            if (switchRoomPictures.size() > 0) {
                //旧数据删除，插入新数据
                if(-1!=switchRoomPictureMapper.deleteBatch(idsMap)){
                    switchRoomPictureMapper.insertList(switchRoomPictures);
                }
            }
            if (switchRoomTypes.size() > 0) {
                //旧数据删除，插入新数据
                if(-1!=switchRoomTypeMapper.deleteBatch(idsMap)){
                    switchRoomTypeMapper.insertList(switchRoomTypes);
                }
                //物理房型保存至redis(for对数据)
                /*Map<String,SwitchRoomTypeDto> putMap = redisTemplate.opsForValue().get(CommonConstants.SWITCH_HOTEL_ROOM)
                        ==null?null:(Map)redisTemplate.opsForValue().get(CommonConstants.SWITCH_HOTEL_ROOM);
                if(null != putMap && putMap.size()>0){
                    putMap.putAll(redisMap);
                }else{
                    putMap=redisMap;
                }
                redisTemplate.opsForValue().set(CommonConstants.SWITCH_HOTEL_ROOM,putMap);
*/
            }
            if (switchRoomTypeFacilities.size() > 0) {
                switchRoomTypeFacilityMapper.insertList(switchRoomTypeFacilities);
            }
        }
        return new Result<>();
    }

    /**
     * 新增子物理房型
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> createBasicRoom(CreateBasicRoomVo createBasicRoomVo) {
        Map<String, Object> map = new HashMap<>();
        if (createBasicRoomVo.getChildHotelId() == 0) {
            return new Result<>("子酒店ID不能为空");
        }
        map.put("childHotelId", createBasicRoomVo.getChildHotelId());
        if (createBasicRoomVo.getMasterHotelId() == 0) {
            return new Result<>("母酒店Id不能为空");
        }
        map.put("masterHotelId", createBasicRoomVo.getMasterHotelId());
        int masterBasicRoomId = createBasicRoomVo.getMasterBasicRoomId();
        if (masterBasicRoomId == 0) {
            return new Result<>("母房型ID不能为空");
        }
        int[] masterBasicRoomIds = {masterBasicRoomId};
        map.put("masterBasicRoomIds", masterBasicRoomIds);
        Map<String, Object> data = new HashMap<>(map);
        data.put("currency", "CNY");
        data.put("opClientIP", "127.0.0.1");
        log.info("=======拉取配置====={}",profile);
        String result = SwitchsHttpUtils.sendRequest(data, "createBasicRoom", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        if (resultStatusInfoVo.getResultCode() != 0) {
            logger.info("新增子物理房型错误信息{}", resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }
        JSONArray jsonArray = jsonObject.getJSONArray("basicRoomIds");
        Integer[] list = new Integer[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            list[i] = jsonArray.getInteger(i);
        }
        return new Result<>(list);
    }

    /**
     * 更新子物理房型
     *
     * @param updateBasicRoomVo
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> updateBasicRoom(UpdateBasicRoomVo updateBasicRoomVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = updateBasicRoomVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        int basicRoomTypeID = updateBasicRoomVo.getBasicRoomTypeID();
        if (basicRoomTypeID == 0) {
            return new Result<>("子酒店的物理房型不能为空");
        }
        map.put("basicRoomTypeID", basicRoomTypeID);
        map.put("submitor", updateBasicRoomVo.getSubmitor());
        map.put("submitorType", updateBasicRoomVo.getSubmitorType());
        int person = updateBasicRoomVo.getPerson();
        if (person > 0) {
            map.put("person", person);
        }
        int roomQuantity = updateBasicRoomVo.getRoomQuantity();
        if (roomQuantity > 0) {
            map.put("roomQuantity", roomQuantity);
        }
        int hasWindow = updateBasicRoomVo.getHasWindow();
        if (hasWindow != -1) {
            map.put("hasWindow", hasWindow);
        }
        int areaRange = updateBasicRoomVo.getAreaRange();
        if (areaRange >= 2 && areaRange <= 600) {
            map.put("areaRange", areaRange);
        }
        int addBedFee = updateBasicRoomVo.getAddBedFee();
        if (addBedFee != -2) {
            map.put("addBedFee", addBedFee);
        }
        int hasWirelessBroadnet = updateBasicRoomVo.getHasWirelessBroadnet();
        if (hasWirelessBroadnet != 0) {
            map.put("hasWirelessBroadnet", hasWirelessBroadnet);
        }
        int hasWiredBroadnet = updateBasicRoomVo.getHasWiredBroadnet();
        if (hasWiredBroadnet != 0) {
            map.put("hasWiredBroadnet", hasWiredBroadnet);
        }
        double broadnetFeeDetail = updateBasicRoomVo.getBroadnetFeeDetail();
        if (hasWirelessBroadnet == 3 || hasWiredBroadnet == 3) {
            if (broadnetFeeDetail <= 0) {
                return new Result<>("国内酒店网络收费时，不能为空");
            } else {
                map.put("broadnetFeeDetail", broadnetFeeDetail);
            }
        }
        int smoke = updateBasicRoomVo.getSmoke();
        if (smoke != 0) {
            map.put("smoke", smoke);
        }
        List<BasicRoomBedTypeVo> basicRoomBedType = updateBasicRoomVo.getBasicRoomBedType();
        if (!ObjectUtils.isEmpty(basicRoomBedType) && basicRoomBedType.size() > 0) {
            map.put("basicRoomBedType", basicRoomBedType);
        }
        String result = SwitchsHttpUtils.sendRequest(map, "updateBasicRoom", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }

    /**
     * 设置售卖房型上下线
     *
     * @param setRoomOnlineOfflineVo
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> setRoomOnlineOffline(SetRoomOnlineOfflineVo setRoomOnlineOfflineVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = setRoomOnlineOfflineVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        int roomTypeId = setRoomOnlineOfflineVo.getRoomTypeId();
        if (roomTypeId == 0) {
            return new Result<>("售卖房型id不能为空");
        }
        map.put("roomTypeId", roomTypeId);
        String channel = setRoomOnlineOfflineVo.getChannel();
        if (StringUtils.isEmpty(channel)) {
            return new Result<>("分销渠道不能为空");
        }
        map.put("channel", channel);
        map.put("roomStatus", setRoomOnlineOfflineVo.getRoomStatus());
        String result = SwitchsHttpUtils.sendRequest(map, "setRoomOnlineOffline", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }

    /**
     * 更改售卖房型渠道名称
     *
     * @param map
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> updateRoomSaleName(Map<String, Object> map) {
        String result = SwitchsHttpUtils.sendRequest(map, "updateRoomSaleName", profile);
        logger.info("更改售卖房型渠道名称");
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }

    /**
     * 设置房型库存房态共享
     *
     * @param
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> setRoomShare(SetRoomShareVo setRoomShareVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = setRoomShareVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        int roomId = setRoomShareVo.getRoomId();
        if (roomId == 0) {
            return new Result<>("售卖房型id不能为空");
        }
        map.put("roomId", roomId);
        String shareType = setRoomShareVo.getShareType();
        if (StringUtils.isEmpty(shareType)) {
            return new Result<>("共享与房态不能为空");
        }
        map.put("shareType", shareType);
        System.out.println(setRoomShareVo.isShare());
        map.put("isShare", setRoomShareVo.isShare());
        String baseChannel = setRoomShareVo.getBaseChannel();
        if (StringUtils.isEmpty(baseChannel)) {
            return new Result<>("库存和房态的基准渠道不能为空");
        }
        map.put("baseChannel", baseChannel);
        String result = SwitchsHttpUtils.sendRequest(map, "setRoomShare", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }

    /**
     * 创建售卖房型
     *
     * @param createRoomVo
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<CreateRoomResultVo> createRoom(CreateRoomVo createRoomVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = createRoomVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        int basicRoomTypeId = createRoomVo.getBasicRoomTypeId();
        if (basicRoomTypeId == 0) {
            return new Result<>("子酒店的物理房型id不能为空");
        }
        map.put("basicRoomTypeId", basicRoomTypeId);
        map.put("roomTypeId", createRoomVo.getRoomTypeId());
        map.put("relationRoomId", createRoomVo.getRelationRoomId());
        map.put("priceType", createRoomVo.getPriceType());
        Integer[] rateCodePropertyValueIDList = createRoomVo.getRateCodePropertyValueIDList();
        if (rateCodePropertyValueIDList.length < 1) {
            return new Result<>("房型属性值不能为空");
        }
        int mealCount = createRoomVo.getMealCount();
        boolean hav_six = ArrayUtils.contains(rateCodePropertyValueIDList, 6);
        boolean hav_eight = ArrayUtils.contains(rateCodePropertyValueIDList, 8);
        //如果早餐属性选择6和8 必须设置餐食份
        if (hav_six || hav_eight) {
            map.put("mealCount", mealCount);
        }
        Integer[] applicabilityList = createRoomVo.getApplicabilityList();
        if (applicabilityList.length < 1) {
            return new Result<>("国内酒店设置的适用人群属性不能为空");
        }
        map.put("rateCodePropertyValueIDList", rateCodePropertyValueIDList);
        map.put("applicabilityInfo", createRoomVo.getApplicabilityInfo());
        map.put("purchaseSourceID", createRoomVo.getPurchaseSourceID());
        map.put("applicabilityList", applicabilityList);
        //如果有包含自定义价格体系
        String priceSystemName = createRoomVo.getPriceSystemName();
        if (!StringUtils.isEmpty(priceSystemName)) {
            map.put("priceSystemName", priceSystemName);
        }
        //定义黑名单列表
        Integer[] blackChannelList = createRoomVo.getBlackChannelList();
        if (blackChannelList.length > 0) {
            map.put("blackChannelList", blackChannelList);
        }
        String result = SwitchsHttpUtils.sendRequest(map, "createRoom", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        CreateRoomResultVo createRoomResultVo = new CreateRoomResultVo();
        createRoomResultVo.setResultStatusInfoVo(resultStatusInfoVo);
        logger.info("创建售卖房型");
        if (resultStatusInfoVo.getResultCode() == 0) {
            int roomTypeId = jsonObject.getInteger("roomTypeId");
            String roomName = jsonObject.getString("roomName");
            createRoomResultVo.setRoomTypeId(roomTypeId);
            createRoomResultVo.setRoomName(roomName);
        }
        //说明调用接口失败
        return new Result<>(createRoomResultVo);
    }

    /**
     * 更新售卖房型
     *
     * @param updateRateCode
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> updateRateCode(UpdateRateCodeVo updateRateCode) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = updateRateCode.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        int roomTypeId = updateRateCode.getRoomTypeId();
        if (roomTypeId == 0) {
            return new Result<>("售卖房型id不能为空");
        }
        map.put("roomTypeId", roomTypeId);
        String roomName = updateRateCode.getRoomName();
        if (!StringUtils.isEmpty(roomName)) {
            map.put("roomName", roomName);
        }
        map.put("setPurchaseSourceRate", updateRateCode.isSetPurchaseSourceRate());
        map.put("purchaseSourceId", updateRateCode.getPurchaseSourceId());
        //是否设置入住人数
        if (updateRateCode.isSetPersonRate()) {
            map.put("personRateProperty", updateRateCode.getPersonRateProperty());
        }
        map.put("setPersonRate", updateRateCode.isSetPersonRate());
        //是否设置床型
        if (updateRateCode.isSetBedTypeRate()) {
            map.put("bedTypeRateProperty", updateRateCode.getBedTypeRateProperty());
        }
        map.put("setBedTypeRate", updateRateCode.isSetBedTypeRate());
        //是否设置餐食
        if (updateRateCode.isSetBreakfastRate()) {
            String breakfastRateProperty = updateRateCode.getBreakfastRateProperty();
            map.put("breakfastRateProperty", breakfastRateProperty);
            boolean hav_six = breakfastRateProperty.contains("6");
            boolean hav_eight = breakfastRateProperty.contains("8");
            //如果早餐属性选择6和8 必须设置餐食份
            if (hav_six || hav_eight) {
                map.put("mealCount", updateRateCode.getMealCount());
            }
        }
        //设置默认餐食
        map.put("setBreakfastRate", updateRateCode.isSetBreakfastRate());
        map.put("setBreakfastDefault", updateRateCode.isSetBreakfastDefault());
        //是否设置使用人群
        if (updateRateCode.isSetApplicabilityRate()) {
            map.put("applicabilityRateProperty", updateRateCode.getApplicabilityRateProperty());
        }
        map.put("setApplicabilityRate", updateRateCode.isSetApplicabilityRate());
        map.put("applicabilityInfo", updateRateCode.getApplicabilityInfo());
        map.put("applicabilityList", updateRateCode.getApplicabilityList());
        //是否设置房型名称
        if (updateRateCode.isSetRoomNameRemarkRate()) {
            map.put("roomNameRemarkRateProperty", updateRateCode.getRoomNameRemarkRateProperty());
        }
        //是否设置促销
        if (updateRateCode.isSetPreferentialRate()) {
            map.put("preferentialRateProperty", updateRateCode.getPreferentialRateProperty());
        }
        map.put("setPreferentialRate", updateRateCode.isSetPreferentialRate());
        //是否设置价格体系
        if (updateRateCode.isSetShowChannelRate()) {
            map.put("showChannelRateProperty", updateRateCode.getShowChannelRateProperty());
        }
        map.put("setShowChannelRate", updateRateCode.isSetShowChannelRate());
        //是否自定义价格体系
        if (!StringUtils.isEmpty("priceSystemName")) {
            map.put("priceSystemName", updateRateCode.getPriceSystemName());
        }
        //是否自定义黑名单列表
        if (updateRateCode.getBlackChannelList().length > 0) {
            map.put("blackChannelList", updateRateCode.getBlackChannelList());
        }
        String result = SwitchsHttpUtils.sendRequest(map, "updateRateCode", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(result);
        logger.info("======调用携程更新售卖房型接口====");
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }

    /**
     * 更新房型售卖规则
     *
     * @param setRoomSaleRuleVo
     * @return
     */
   /* @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))*/
    public Result<Object> setRoomSaleRuleOld(SetRoomSaleRuleVo setRoomSaleRuleVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = setRoomSaleRuleVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        //售卖房型列表
        List<RoomTypeVo> roomTypeList = setRoomSaleRuleVo.getRoomTypeList();
        for (RoomTypeVo roomTypeVo : roomTypeList) {
            if (roomTypeVo.getRoomTypeId() == 0) {
                return new Result<>("请传有效的售卖房型Id");
            }
            if (StringUtils.isEmpty(roomTypeVo.getRoomTypeName())) {
                return new Result<>("请传有效的售卖房型名称");
            }
        }
        map.put("roomTypeList", roomTypeList);
        //规则设置列表
        List<SaleRuleVo> saleRuleVos = setRoomSaleRuleVo.getSaleRuleList();
        List<Object> list = new ArrayList<>();
        for (SaleRuleVo saleRuleVo : saleRuleVos) {
            String channelType = saleRuleVo.getChannelType();
            //crip渠道
            if (channelType.equals("ctrip")) {
                SaleRuleByCtripVo saleRuleByCtripVo = new SaleRuleByCtripVo();
                saleRuleByCtripVo.setChannelType(channelType);
                //是否设置取消规则
                saleRuleByCtripVo.setSetCancel(saleRuleVo.isSetCancel());
                //是否可以取消 isSetCancel为true必传
                saleRuleByCtripVo.setCanCancel(saleRuleVo.isCanCancel());
                //可取消提前天数
                saleRuleByCtripVo.setCheckInDay(saleRuleVo.getCheckInDay());
                //可取消提前小时数
                saleRuleByCtripVo.setCheckInTime(saleRuleVo.getCheckInTime());
                //可取消扣款类型 Ctrip渠道传0
                saleRuleByCtripVo.setDeductType(saleRuleVo.getDeductType());
                //可取消扣款比例
                saleRuleByCtripVo.setDeductProportion(saleRuleVo.getDeductProportion());
                //逾期取消天数
                saleRuleByCtripVo.setCheckInDay2(saleRuleVo.getCheckInDay2());
                //期取消小时数
                saleRuleByCtripVo.setCheckInTime2(saleRuleVo.getCheckInTime2());
                //逾期扣款类型
                saleRuleByCtripVo.setDeductType2(saleRuleVo.getDeductType2());
                //可取消扣款比例
                saleRuleByCtripVo.setDeductProportion2(saleRuleVo.getDeductProportion2());
                saleRuleByCtripVo.setSetAutoChange(saleRuleVo.isSetAutoChange());
                //是否允许渠道价格自动变更
                saleRuleByCtripVo.setAutoChange(saleRuleVo.isAutoChange());
                //自动变更操作类型 1 加 2 减 3 乘 4 除
                saleRuleByCtripVo.setFormula(saleRuleVo.getFormula());
                //自动变更 修改值，formula为4时，不能传0
                if (saleRuleVo.getFormula() == 4 && saleRuleVo.getModifyValue() == 0) {
                    return new Result<>("自动变更 修改值，formula为4时，不能传0");
                }
                saleRuleByCtripVo.setModifyValue(saleRuleVo.getModifyValue());
                saleRuleByCtripVo.setBaseChannel(saleRuleVo.getBaseChannel());
                //是否设置最晚预定时间
                saleRuleByCtripVo.setSetLastBookTime(saleRuleVo.isSetLastBookTime());
                //最晚预定天数
                saleRuleByCtripVo.setLastBookDay(saleRuleVo.getLastBookDay());
                //最晚预定小时数
                saleRuleByCtripVo.setLastBookTime(String.valueOf(saleRuleVo.getLastBookTime()));
                //是否设置最晚确认时间
                saleRuleByCtripVo.setSetLastConfirmTime(saleRuleVo.isSetLastConfirmTime());
                //最晚确认天数
                saleRuleByCtripVo.setLastConfirmDay(saleRuleVo.getLastConfirmDay());
                //最晚确认小时数
                saleRuleByCtripVo.setLastConfirmTime(saleRuleVo.getLastConfirmTime());
                //是否设置可见人群
                saleRuleByCtripVo.setSetLimitVisiable(saleRuleVo.isSetLimitVisiable());
                if (saleRuleVo.isSetLimitVisiable() && saleRuleVo.isDeleteLimitVisiable()) {
                    return new Result<>("isDeleteLimitVisiable和isSetLimitVisiable为互斥关系，不能同时为true，可以同时为false");
                }
                //是否删除房型上可见人群设置
                saleRuleByCtripVo.setDeleteLimitVisiable(saleRuleVo.isDeleteLimitVisiable());
                if (saleRuleVo.isSetLimitVisiable()) {
                    saleRuleByCtripVo.setCModel(saleRuleVo.getCModel());
                    saleRuleByCtripVo.setTModel(saleRuleVo.getTModel());
                }
                list.add(saleRuleByCtripVo);
            } else {//Qunar,B2B,分销A
                SaleRuleByOtherVo saleRuleByOtherVo = new SaleRuleByOtherVo();
                saleRuleByOtherVo.setChannelType(channelType);
                //是否设置取消规则
                saleRuleByOtherVo.setSetCancel(saleRuleVo.isSetCancel());
                //是否设置售卖时段
                saleRuleByOtherVo.setSetSaleTime(saleRuleVo.isSetSaleTime());
                if (saleRuleVo.isSetSaleTime()) {
                    if (ObjectUtils.isEmpty(saleRuleVo.getStartTime())) {
                        return new Result<>("售卖开始时间不能为空");
                    }
                    if (ObjectUtils.isEmpty(saleRuleVo.getEndTime())) {
                        return new Result<>("售卖结束时间不能为空");
                    }
                    //0是当日，1是次日
                    //0时，startTime 必须小于endTime
                    //1时，startTime 必须大于endTime
                    saleRuleByOtherVo.setEndDateType(saleRuleVo.getEndDateType());
                    DateFormat dateFormat = new SimpleDateFormat("HH:mm");
                    Date startTime = null;
                    Date endTime = null;
                    try {
                        startTime = dateFormat.parse(saleRuleVo.getStartTime());
                        endTime = dateFormat.parse(saleRuleVo.getEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                        return new Result<>(e);
                    }
                    int i = startTime.compareTo(endTime);
                    if (saleRuleVo.getEndDateType() == 0 && i > 0) {//当日
                        return new Result<>("设置当日售卖时段时，开始时间必须不能大于结束时间");
                    }
                    if (saleRuleVo.getEndDateType() == 1 && i < 0) {//次日
                        return new Result<>("设置次日售卖时段时，开始时间必须不能小于结束时间");
                    }
                    //售卖开始时间
                    saleRuleByOtherVo.setStartTime(saleRuleVo.getStartTime());
                    //售卖结束时间
                    saleRuleByOtherVo.setEndTime(saleRuleVo.getEndTime());
                }
                //是否设置售卖限制
                saleRuleByOtherVo.setSetLimit(saleRuleVo.isSetLimit());
                //是否设置售卖限制
                //是否False为不设置，true为设置
                //限制类型：1 限制 0 不限制
                saleRuleByOtherVo.setLimitType(saleRuleVo.getLimitType());
                //imitType才用，售卖限制提前天数,范围0~999
                saleRuleByOtherVo.setAdvanceDay(saleRuleVo.getAdvanceDay());
                //售卖限制提前小时数，例如”20”,0~24
                saleRuleByOtherVo.setAdvanceTime(saleRuleVo.getAdvanceTime());
                //专0
                saleRuleByOtherVo.setAdvanceType(saleRuleVo.getAdvanceType());
                //是否设置连住限制
                saleRuleByOtherVo.setSetLast(saleRuleVo.isSetLast());
                //最少连住天数
                saleRuleByOtherVo.setMinLastDay(saleRuleVo.getMinLastDay());
                //最大连住天数
                saleRuleByOtherVo.setMaxLastDay(saleRuleVo.getMaxLastDay());
                //是否设置间数限制
                saleRuleByOtherVo.setSetBookRoomNum(saleRuleVo.isSetBookRoomNum());
                //最少预定间数
                saleRuleByOtherVo.setMinBookRoomNum(saleRuleVo.getMinBookRoomNum());
                //最大预定间数
                saleRuleByOtherVo.setMaxBookRoomNum(saleRuleVo.getMaxBookRoomNum());
                //是否可以取消 isSetCancel为true必传
                saleRuleByOtherVo.setCanCancel(saleRuleVo.isCanCancel());
                //可取消提前天数
                saleRuleByOtherVo.setCheckInDay(saleRuleVo.getCheckInDay());
                saleRuleByOtherVo.setCheckInTime(saleRuleVo.getCheckInTime());
                //可取消扣款类型 Ctrip渠道传0
                saleRuleByOtherVo.setDeductType(saleRuleVo.getDeductType());
                //可取消扣款比例
                saleRuleByOtherVo.setDeductProportion(saleRuleVo.getDeductProportion());
                //逾期取消天数
                saleRuleByOtherVo.setCheckInDay2(saleRuleVo.getCheckInDay2());
                //期取消小时数
                saleRuleByOtherVo.setCheckInTime2(saleRuleVo.getCheckInTime2());
                //逾期扣款类型
                saleRuleByOtherVo.setDeductType2(saleRuleVo.getDeductType2());
                //可取消扣款比例
                saleRuleByOtherVo.setDeductProportion2(saleRuleVo.getDeductProportion2());
                saleRuleByOtherVo.setSetAutoChange(saleRuleVo.isSetAutoChange());
                if (saleRuleVo.isSetAutoChange() && saleRuleVo.isAutoChange()) {
                    return new Result<>("can't set price strategy!,isSetAutoChange为true,autoChange不能也为true");
                }
                //是否允许渠道价格自动变更
                saleRuleByOtherVo.setAutoChange(saleRuleVo.isAutoChange());
                //自动变更操作类型 1 加 2 减 3 乘 4 除
                saleRuleByOtherVo.setFormula(saleRuleVo.getFormula());
                //自动变更 修改值，formula为4时，不能传0
                if (saleRuleVo.getFormula() == 4 && saleRuleVo.getModifyValue() == 0) {
                    return new Result<>("自动变更 修改值，formula为4时，不能传0");
                }
                saleRuleByOtherVo.setModifyValue(saleRuleVo.getModifyValue());
                saleRuleByOtherVo.setBaseChannel(saleRuleVo.getBaseChannel());
                //是否设置最晚预定时间
                saleRuleByOtherVo.setSetLastBookTime(saleRuleVo.isSetLastBookTime());
                //最晚预定天数
                saleRuleByOtherVo.setLastBookDay(saleRuleVo.getLastBookDay());
                //是否设置最晚确认时间
                saleRuleByOtherVo.setSetLastConfirmTime(saleRuleVo.isSetLastConfirmTime());
                //最晚确认天数
                saleRuleByOtherVo.setLastConfirmDay(saleRuleVo.getLastConfirmDay());
                //最晚确认小时数
                saleRuleByOtherVo.setLastConfirmTime(saleRuleVo.getLastConfirmTime());
                list.add(saleRuleByOtherVo);
            }
        }
        if (list.size() == 0) {
            return new Result<>("规则设置列表不能为空");
        }
        map.put("saleRuleList", list);
        map.put("setCtripDailyRule", setRoomSaleRuleVo.isSetCtripDailyRule());
        String result = SwitchsHttpUtils.sendRequest(map, "setRoomSaleRule", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        //说明调用接口失败
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }
    /**
     * 更新房型售卖规则
     *
     * @param setRoomSaleRuleVo
     * @return
     */
   /* @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))*/
    public Result<Object> setRoomSaleRule(SetRoomSaleRuleVo setRoomSaleRuleVo) {
        Map<String, Object> map = new HashMap<>();
        int hotelId = setRoomSaleRuleVo.getHotelId();
        if (hotelId == 0) {
            return new Result<>("子酒店不能为空");
        }
        map.put("hotelId", hotelId);
        //售卖房型列表
        List<RoomTypeVo> roomTypeList = setRoomSaleRuleVo.getRoomTypeList();
        for (RoomTypeVo roomTypeVo : roomTypeList) {
            if (roomTypeVo.getRoomTypeId() == 0) {
                return new Result<>("请传有效的售卖房型Id");
            }
            if (StringUtils.isEmpty(roomTypeVo.getRoomTypeName())) {
                return new Result<>("请传有效的售卖房型名称");
            }
        }
        map.put("roomTypeList", roomTypeList);
        map.put("setCtripDailyRule",setRoomSaleRuleVo.isSetCtripDailyRule());
        //封装售卖规则
        List<Map<String,Object>> saleRuleList=new ArrayList<>();
        //规则设置列表
        List<SaleRuleVo> saleRuleVos = setRoomSaleRuleVo.getSaleRuleList();
        for (SaleRuleVo saleRuleVo : saleRuleVos) {
            Map<String,Object> saleRule=new HashMap<>();
            String channelType = saleRuleVo.getChannelType();
            saleRule.put("channelType",channelType);
            //crip渠道
            if (channelType.equals("ctrip")) {
                saleRule.put("isSetCancel",saleRuleVo.isSetCancel());
                //可取消规则
                if(saleRuleVo.isSetCancel()){
                    log.info("===========封装可取消规则==========");
                    saleRule.put("canCancel",saleRuleVo.isCanCancel());
                    saleRule.put("checkInDay",saleRuleVo.getCheckInDay());
                    saleRule.put("checkInTime",saleRuleVo.getCheckInTime());
                    saleRule.put("deductType",saleRuleVo.getDeductType());
                    saleRule.put("deductProportion",0);
                    saleRule.put("checkInDay2",saleRuleVo.getCheckInDay2());
                    saleRule.put("checkInTime2",saleRuleVo.getCheckInTime2());
                    saleRule.put("deductType2",saleRuleVo.getDeductType2());
                    saleRule.put("deductProportion2",saleRuleVo.getDeductProportion2());

                }else{//不可取消规则
                    saleRule.put("canCancel",saleRuleVo.isCanCancel());
                    //扣全款
                    saleRule.put("deductType2",1);
                }
                saleRule.put("isSetAutoChange",saleRuleVo.isSetAutoChange());
                if(saleRuleVo.isSetAutoChange()){
                    saleRule.put("autoChange",false);
                }else{
                    saleRule.put("autoChange",saleRuleVo.isAutoChange());
                }
                saleRule.put("formula",saleRuleVo.getFormula());
                saleRule.put("modifyValue",saleRuleVo.getModifyValue());
                saleRule.put("baseChannel", ObjectUtils.isEmpty(saleRuleVo.getBaseChannel())?"":saleRuleVo.getBaseChannel());
                //预定时间设置
                saleRule.put("isSetLastBookTime",saleRuleVo.isSetLastBookTime());
                saleRule.put("lastBookDay",saleRuleVo.getLastBookDay());
                saleRule.put("lastBookTime", ObjectUtils.isEmpty(saleRuleVo.getLastBookTime())?"23:00":saleRuleVo.getLastBookTime());
                //最晚确认时间确认
                saleRule.put("isSetLastConfirmTime",saleRuleVo.isSetLastConfirmTime());
                saleRule.put("lastConfirmDay",saleRuleVo.getLastConfirmDay());
                saleRule.put("lastConfirmTime", ObjectUtils.isEmpty(saleRuleVo.getLastConfirmTime())?"18:00":saleRuleVo.getLastConfirmTime());
                //是否设置可见人群
                saleRule.put("isSetLimitVisiable",saleRuleVo.isSetLimitVisiable());
                if (saleRuleVo.isSetLimitVisiable() && saleRuleVo.isDeleteLimitVisiable()) {
                    return new Result<>("isDeleteLimitVisiable和isSetLimitVisiable为互斥关系，不能同时为true，可以同时为false");
                }
                //是否删除房型上可见人群设置
                saleRule.put("isDeleteLimitVisiable",saleRuleVo.isDeleteLimitVisiable());
                if (saleRuleVo.isSetLimitVisiable()) {
                    if(!ObjectUtils.isEmpty(saleRuleVo.getCModel())){
                        saleRule.put("cModel",saleRuleVo.getCModel());
                    }
                    if(!ObjectUtils.isEmpty(saleRuleVo.getCModel())){
                        saleRule.put("tModel",saleRuleVo.getTModel());
                    }
                }
                saleRuleList.add(saleRule);
            } else {//Qunar,B2B,分销A
                saleRule.put("isSetCancel",saleRuleVo.isSetCancel());
                //是否设置售卖时段
                saleRule.put("isSetSaleTime",saleRuleVo.isSetSaleTime());
                if (saleRuleVo.isSetSaleTime()) {
                    if (ObjectUtils.isEmpty(saleRuleVo.getStartTime())) {
                        return new Result<>("售卖开始时间不能为空");
                    }
                    if (ObjectUtils.isEmpty(saleRuleVo.getEndTime())) {
                        return new Result<>("售卖结束时间不能为空");
                    }
                    //0是当日，1是次日
                    //0时，startTime 必须小于endTime
                    //1时，startTime 必须大于endTime
                    saleRule.put("endDateType",saleRuleVo.getEndDateType());
                    DateFormat dateFormat = new SimpleDateFormat("HH:mm");
                    Date startTime = null;
                    Date endTime = null;
                    try {
                        startTime = dateFormat.parse(saleRuleVo.getStartTime());
                        endTime = dateFormat.parse(saleRuleVo.getEndTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                        return new Result<>(e);
                    }
                    int i = startTime.compareTo(endTime);
                    if (saleRuleVo.getEndDateType() == 0 && i > 0) {//当日
                        return new Result<>("设置当日售卖时段时，开始时间必须不能大于结束时间");
                    }
                    if (saleRuleVo.getEndDateType() == 1 && i < 0) {//次日
                        return new Result<>("设置次日售卖时段时，开始时间必须不能小于结束时间");
                    }
                    //售卖开始时间
                    saleRule.put("startTime",saleRuleVo.getStartTime());
                    //售卖结束时间
                    saleRule.put("endTime",saleRuleVo.getEndTime());
                }
                //是否设置售卖限制
                saleRule.put("isSetLimit",saleRuleVo.isSetLimit());
                saleRule.put("limitType",saleRuleVo.getLimitType());
                //设置售卖限制
                if(saleRuleVo.getLimitType()==1){
                    saleRule.put("advanceDay",saleRuleVo.getAdvanceDay());
                    saleRule.put("advanceTime",saleRuleVo.getAdvanceTime());
                    saleRule.put("advanceType",0);
                }
                //设置连住限制
                saleRule.put("isSetLast",saleRuleVo.isSetLast());
                saleRule.put("minLastDay",saleRuleVo.getMinLastDay());
                saleRule.put("maxLastDay",saleRuleVo.getMaxLastDay());
                //是否设置间数限制
                saleRule.put("isSetBookRoomNum",saleRuleVo.isSetBookRoomNum());
                saleRule.put("minBookRoomNum",saleRuleVo.getMinBookRoomNum());
                saleRule.put("maxBookRoomNum",saleRuleVo.getMaxBookRoomNum());
                //可取消规则
                if(saleRuleVo.isSetCancel()){
                    log.info("===========封装可取消规则==========");
                    saleRule.put("canCancel",saleRuleVo.isCanCancel());
                    saleRule.put("checkInDay",saleRuleVo.getCheckInDay());
                    saleRule.put("checkInTime",saleRuleVo.getCheckInTime());
                    saleRule.put("deductType",saleRuleVo.getDeductType());
                    saleRule.put("deductProportion",saleRuleVo.getDeductProportion());
                    saleRule.put("checkInDay2",saleRuleVo.getCheckInDay2());
                    saleRule.put("checkInTime2",saleRuleVo.getCheckInTime2());
                    saleRule.put("deductType2",saleRuleVo.getDeductType2());
                    saleRule.put("deductProportion2",99);
                }else{//不可取消
                    saleRule.put("canCancel",saleRuleVo.isCanCancel());
                }
                //设置是否自动变更
                saleRule.put("isSetAutoChange",saleRuleVo.isSetAutoChange());
                if(saleRuleVo.isSetAutoChange()){
                    saleRule.put("autoChange",false);
                }else{
                    saleRule.put("autoChange",saleRuleVo.isAutoChange());
                }
                //预定时间设置
                saleRule.put("isSetLastBookTime",saleRuleVo.isSetLastBookTime());
                saleRule.put("lastBookDay",saleRuleVo.getLastBookDay());
                saleRule.put("lastBookTime", ObjectUtils.isEmpty(saleRuleVo.getLastBookTime())?"23:00":saleRuleVo.getLastBookTime());
                //最晚确认时间确认
                saleRule.put("isSetLastConfirmTime",saleRuleVo.isSetLastConfirmTime());
                saleRule.put("lastConfirmDay",saleRuleVo.getLastConfirmDay());
                saleRule.put("lastConfirmTime", ObjectUtils.isEmpty(saleRuleVo.getLastConfirmTime())?"18:00":saleRuleVo.getLastConfirmTime());
                saleRuleList.add(saleRule);
            }
        }
        if (saleRuleList.size() == 0) {
            return new Result<>("规则设置列表不能为空");
        }
        map.put("saleRuleList", saleRuleList);
        String result = SwitchsHttpUtils.sendRequest(map, "setRoomSaleRule", "prod");
        ResultStatusInfoVo resultStatusInfoVo=new ResultStatusInfoVo();
        try{
            //对结构进行格式化
            JSONObject jsonObject = JSONObject.parseObject(result);
            System.out.println(result);
            resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
            //说明调用接口失败
        }catch (Exception e){
            log.debug("=============调用接口更新售卖房型规则接口出现异常，请求的数据为{}", JSON.toJSONString(map));
        }
        int code = (resultStatusInfoVo.getResultCode() == 0) ? CommonConstants.SUCCESS : CommonConstants.REQUEST_ERROR;
        return new Result<>(resultStatusInfoVo.getResultMsg(), code);
    }
    /**
     * 获取房型售卖规则
     *
     * @param map
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> getRoomSaleRule(Map<String, Object> map) {
        String result = SwitchsHttpUtils.sendRequest(map, "getRoomSaleRule", profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(result);
        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);
        if (resultStatusInfoVo.getResultCode() != 0) {
            logger.info("获取房型售卖规则错误信息{}", resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg());
        }
        List<RoomSaleRuleReturnVo> list = JSONUtils.toList(jsonObject.getJSONArray("roomSaleRuleList"), RoomSaleRuleReturnVo.class);
        //说明调用接口失败
        return new Result<>(list);
    }

    /**
     * 根据子酒店id+子物理房型id 获取母物理房型+母物理房型名称
     * @param hotelId
     * @param basicRoomTypeId
     * @return
     */
    @Override
    public SwitchBasicRoomType selectByBasicId(Integer hotelId, Integer basicRoomTypeId) {
        return switchBasicRoomTypeMapper.selectByHotelIdAndBasicId(hotelId,basicRoomTypeId);
    }

}
